import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Button, Input, Modal, message, Drawer, Icon,Form ,Pagination } from 'antd';
import styles from './index.less';

const ExtendRt = React.lazy(() => import('../extendRt'));
const Search = Input.Search;
@connect(({ question, loading }) => ({
  question,
  loading: loading.effects['question/getQuestionsByQaId'],
}))
class Question extends Component {
  constructor(props) {
    super(props);
    this.state={
      questions:'',
      question: '',
      standardQus:'',
      qaId:'',
      slots:'',
      questionIndex: null,
      isShowQusSlot: null,
      oldQus: '',
      qusList:[],
      isShard:props.isShard?props.isShard:false
    }
  }

  componentWillReceiveProps(nextProps, nextContext) {
    this.setState({
      qusList:nextProps.questions
    })
  }

  addQuestion=(e,isEdit,id)=>{
    e.preventDefault();
    if(!e.target.value){
      return message.error('问题不可为空');
    }
    const  val = e.target.value;
    this.setState({
      question: ''
    },()=>{
      this.props.add(val)
    })
  };

  addQusByEdit=(qaId,val)=>{
    const { dispatch } = this.props;
    const  that = this;
    let arr = [];
    arr=arr.concat(val);
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'question/addQus',
        payload: {id:qaId,questions:arr},
        callback: (res) => {
          console.log(res);
          if(!res.code){
            message.info('添加成功');
            that.props.getQusList(qaId,true)
          }
        }
      })
    })
  };

  fixQuestion=(e)=>{
    this.setState({
      question: e.target.value
    },()=>{
      this.props.fixCommQuestion(this.state.question)
    })
  };

  remove = (e,index,qaId) => {
    this.props.remove(e,index)
  };

  setAsk =(val,index,qaId)=>{
    this.props.setStandardQus(val,index)
  };

  setAskByEdit=(qaId,e)=>{
    const that = this;
    const { dispatch } = that.props;
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'question/topQus',
        payload: {id:qaId,question: e},
        callback: (res) => {
          if(!res.code){
            message.info('修改成功');
            that.delSimQusByEdit(qaId,e,true);
            that.props.getTopQus(qaId)
          }
        }
      })
    })
  };

  alterQuestion=(e,k,index,qaId)=>{
    this.props.modifiQus(e,k,index)
  };

  showQuestionSlot=(e,index)=>{
    this.setState({
      questionIndex: index,
      oldQus: e.target.value
    })
  };

  fixedQuestionByBlur=(e,k,index,qaId)=>{
    if(qaId){
      this.props.fixedQuestionByBlurFromSon(e,k,index,qaId)
      // this.editQusByEdit(e,qaId)
    }
  };

  hideQuestionSlot=(e,index)=>{
    this.setState({
      questionIndex: null
    })
  };

  addSlotToQuestion=(val,index)=>{
    const value = `${this.state.question}<${val}>`;
    this.similarInput.focus();
    this.setState({
      question: value,
    });
  };

  modifiedStandard=(e)=>{
    this.props.modifiedStandard(e.target.value)
  };

  delSimQusByEdit=(qaId,e,isSetTop)=>{
    const { dispatch } = this.props;
    const that = this;
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'question/delQus',
        payload: {id:qaId,question: e},
        callback: (res) => {
          console.log(res);
          if(!res.code){
            if(!isSetTop){
              message.info('删除成功');
            }
            that.props.getQusList(qaId)
          }
        }
      })
    })
  };

  editQusByEdit=(e,qaId)=>{
    const { dispatch } = this.props;
    const that = this;
    const val = e.target.value;
    if(val === that.state.oldQus){
      return false;
    }
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'question/editQus',
        payload: {id:qaId,oldQuestion:that.state.oldQus,question: val},
        callback: (res) => {
          console.log(res);
          if(!res.code){
            message.info('修改成功');
            that.props.getQaList(qaId)
          }
        }
      })
    })
  };

  addSlotToNomalQuestion=(name)=>{
    this.standardInput.focus();
    this.props.addSlotToNomalQuestion(name)
  };

  setQusSlot=(e,val)=>{
    this.setState({
      isShowQusSlot: e,
      oldQus: val.target.value
    })
  };

  hideQusSlot=()=>{
    this.setState({
      isShowQusSlot: null
    })
  };

  addSlotToSmQuestion=(name,index)=>{
    const resemblanceX = `resemblance${index}`;
    this.refs[resemblanceX].focus();
    this.props.addSlotToSmQuestion(name,index)
  };

  seeMore=()=>{
    this.props.seeMore(true)
  };

  addQus=(qaId,val,isExtend)=>{
    let qus = this.state.question;
    console.log(val);
    if(qus === ''){
      if(isExtend){
        qus = val
      }else{
        return message.error('相似问不可以为空')
      }
    }
    this.setState({
      question: ''
    },()=>{
      this.props.add(qus)
    })
  };

  getQusBySearch=(e)=>{
    this.props.search(e)
  };


  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 2 },
        sm: { span: 22, offset: 2 },
      },
    };
    const {questions,slots,standardQus,qaId,isShowMore,total,isTowDrawer,isShard}= this.props;
    let arr = [];
    arr=  arr.concat(questions);
    arr.unshift(standardQus);
    const {isShowQusSlot,qusList} = this.state;
    const formItems = questions.map((k, index) => (
      <Form.Item
        {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
        label={index === 0 ? '相似问' : ''}
        required={false}
        key={index}
      >
        <div>
          <Input
            value={k}
            key={index}
            style={{ width: '88%' }}
            placeholder="请输入相似问题"
            ref={`resemblance${index}`}
            className={styles.inputItem}
            disabled={isShard}
            onFocus={e=>this.showQuestionSlot(e,index)}
            onChange={qaId?e=>this.alterQuestion(e,k,index,qaId):e=>this.alterQuestion(e,k,index)}
            onBlur={qaId?e=>this.fixedQuestionByBlur(e,k,index,qaId):e=>this.fixedQuestionByBlur(e,k,index)}
          />
          <span>
            <Icon
              className="dynamic-delete-button"
              type="close-circle"
              disabled={isShard}
              onClick={qaId?() => this.remove(k,index,qaId):() => this.remove(k,index)}
              style={{fontSize:20,marginLeft:10,cursor:"pointer",marginTop:5}}
            />
            <Icon
              type="arrow-up"
              disabled={isShard}
              onClick={qaId?()=>this.setAsk(k,index,qaId):()=>this.setAsk(k,index,qaId)}
              style={{fontSize:20,marginLeft:10,cursor:"pointer",marginTop:5}}
            />
          </span>
        </div>
        {index === this.state.questionIndex ?(
          <div>
            {
              slots.map((slotItem)=>{
                return (
                  <Button key={index} disabled={isShard} htmlType='button' size="small" style={{marginRight:10}} onClick={()=>this.addSlotToSmQuestion(slotItem.name,index)}>&lt;{slotItem.name}&gt;</Button>
                )
              })
            }
          </div>
        ) : null }
      </Form.Item>
    ));
    return (
      <Suspense fallback={<PageLoading />}>
        {!isTowDrawer?"":<div style={{paddingLeft:51,marginBottom:10}}>
          <ExtendRt overall={2} questions={arr} intellectualId={qaId} templateData={(val)=>this.addQus(qaId,val,true)} />
          <Search
            placeholder="请输入关键字"
            style={{ width: 300,marginLeft:10 }}
            onPressEnter={(e)=>this.getQusBySearch(e)}
          />
        </div>
        }
        <Form>
          <Form.Item {...formItemLayoutWithOutLabel}>
            <Row>
              <Col span={21}>
                <Input
                  value={this.state.question}
                  className={styles.inputItem}
                  onChange={e=>this.fixQuestion(e)}
                  onFocus={(e)=>this.setQusSlot('sm',e)}
                  placeholder="请输入相似问题，点击回车键继续添加"
                  ref={(input) => { this.similarInput = input; }}
                  onPressEnter={e=>this.addQuestion(e,false)}
                />
                <span>
                  {isShowQusSlot ==='sm'?
                    slots.map((slotItem,index)=>{
                      return (
                        <Button key={index} disabled={isShard} htmlType='button' size="small" style={{display:this.state.isShowSlot,marginRight:10}} onClick={()=>this.addSlotToQuestion(slotItem.name,'')}>&lt;{slotItem.name}&gt;</Button>
                      )
                    })
                    : ''
                  }
                </span>
              </Col>
              <Col span={3}><Icon type="plus-circle"  style={{ fontSize: 20, marginLeft: 10, cursor: 'pointer', marginTop: 5 }} onClick={qaId?()=>this.addQus(qaId):()=>this.addQus()} />{<ExtendRt questions={arr}  intellectualId={qaId} templateData={(val)=>this.addQus(qaId,val,true)} overall={1} />}</Col>
            </Row>
          </Form.Item>
          <Form.Item label='标准问' {...formItemLayout}>
            <Input
              disabled={isShard}
              value={standardQus}
              style={{ width: '88%' }}
              placeholder="请添加标准问"
              className={styles.inputItem}
              ref={(e)=>{this.standardInput = e;}}
              onFocus={(e)=>this.setQusSlot('qus',e)}
              onChange={(e)=>this.modifiedStandard(e)}
            />
            <div>
              {isShowQusSlot ==='qus'?
                slots.map((slotItem)=>{
                  return (
                    <Button htmlType='button' size="small" disabled={isShard} style={{marginRight:10}} onClick={()=>this.addSlotToNomalQuestion(slotItem.name)}>&lt;{slotItem.name}&gt;</Button>
                  )
                })
                :''
              }
            </div>
          </Form.Item>
          {formItems}
          <Form.Item {...formItemLayoutWithOutLabel}>
            <div style={{textAlign: 'center'}}>
              {isShowMore?<Button htmlType='button' style={{ margin: '0 auto' }} onClick={()=>this.seeMore()}>查看全部相似问</Button>:''}
            </div>
          </Form.Item>
        </Form>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(Question));
